<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="仓库编码" prop="warehouseCode">
        <el-input
          v-model=" queryParams.warehouseCode"
          placeholder="请输入仓库编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-select
          v-model="queryParams.warehouseName"
          placeholder="请选择仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option v-for="(item,index) in warehouseList" :key="index" :label="item.warehouseName"
                     :value="item.warehouseName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="orderCode">
        <el-input
          v-model=" queryParams.orderCode"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提单号" prop="billNo">
        <el-input
          v-model="queryParams.billNo"
          placeholder="请输入提单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="type">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目的地" prop="destination">
        <el-input
          v-model=" queryParams.destination"
          placeholder="请输入目的地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="船名/航次" prop="voyage">
        <el-input
          v-model=" queryParams.voyage"
          placeholder="请输入船名/航次"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="船公司" prop="shippingCompany">
        <el-input
          v-model=" queryParams.shippingCompany"
          placeholder="请输入船公司"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预计离开时间" prop="expectedLeaveDate">
        <el-date-picker clearable
                        style="width: 205px"
                        v-model=" queryParams.expectedLeaveDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预计离开时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预计装箱时间" prop="expectedPackingDate">
        <el-date-picker clearable
                        style="width: 205px"
                        v-model=" queryParams.expectedPackingDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预计装箱时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际装箱时间" prop="actualPackingDate">
        <el-date-picker clearable
                        style="width: 205px"
                        v-model=" queryParams.actualPackingDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择实际装箱时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际进港时间" prop="actualArrivalDate">
        <el-date-picker clearable
                        style="width: 205px"
                        v-model=" queryParams.actualArrivalDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择实际进港时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:order:import']"
        >订单导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          type=""
          plain
          size="mini"
          icon="el-icon-upload2"
          @click="vehicleImport"
          v-hasPermi="['system:vehicle:import']"
        >车辆导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="multiple"
          size="mini"
          icon="el-icon-upload2"
          @click="containerImport"
          v-hasPermi="['system:container:import']"
        >集装箱导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单ID" align="center" prop="orderId"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
      <el-table-column label="订单号" align="center" prop="orderCode"/>
      <el-table-column label="提单号" align="center" prop="billNo"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_order_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="目的地" align="center" prop="destination"/>
      <el-table-column label="船名/航次" align="center" prop="voyage"/>
      <el-table-column label="船公司" align="center" prop="shippingCompany"/>
      <el-table-column label="运输类型" align="center" prop="transportType"/>
      <el-table-column label="已入场车辆数量" align="center" prop="enteredVehicleNum"/>
      <el-table-column label="已出场车辆数量" align="center" prop="exitedVehicleNum"/>
      <el-table-column label="车辆数量" align="center" prop="vehicleNum"/>
      <el-table-column label="集装箱数量" align="center" prop="containerNum"/>
      <el-table-column label="预计离开时间" align="center" prop="expectedLeaveDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedLeaveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计装箱时间" align="center" prop="expectedPackingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedPackingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际装箱时间" align="center" prop="actualPackingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualPackingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际进港时间" align="center" prop="actualArrivalDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualArrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                       fixed="right" width="120"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync=" queryParams.pageNum"
      :limit.sync=" queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 订单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileOrderUploadProgress"
        :on-success="handleFileOrderSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的订单数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importOrderTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileOrderForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 集装箱导入对话框 -->
    <el-dialog :title="containersUpload.title" :visible.sync="containersUpload.open" width="400px" append-to-body>
      <el-upload
        ref="containersUpload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="containersUpload.headers"
        :action="containersUpload.url + '?orderId=' + containersUpload.orderId"
        :disabled="containersUpload.isUploading"
        :on-progress="handleFileContainerUploadProgress"
        :on-success="handleFileContainerSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="containersUpload.updateSupport"/>
            是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importContainerTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileContainersUploadForm">确 定</el-button>
        <el-button @click="containersUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--    车辆-->
    <el-dialog :title="vehicleUpload.title" :visible.sync="vehicleUpload.open" width="400px" append-to-body>
      <el-upload
        ref="vehicleUpload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="vehicleUpload.headers"
        :action="vehicleUpload.url + '?orderId=' + vehicleUpload.orderId"
        :disabled="vehicleUpload.isUploading"
        :on-progress="handleFileVehicleUploadProgress"
        :on-success="handleFileVehicleSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="vehicleUpload.updateSupport"/>
            是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importVehicleTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileVehicleUploadForm">确 定</el-button>
        <el-button @click="vehicleUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/system/order/order'
import { getToken } from '@/utils/auth'
import { allWarehouse } from '@/api/system/warehouse'

export default {
  name: 'Order',
  dicts: ['sys_order_status', 'sys_order_type'],
  data() {
    return {
      warehouseList: [],//所有仓库
      //车辆导入数据
      vehicleUpload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',

        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/order/import/vehicle/data',
        // 订单id
        orderId: 0
      },
      //集装箱导入数据
      containersUpload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/order/import/container/data',
        // 订单id
        orderId: 0
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单-订单表格数据
      orderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        orderCode: null,
        billNo: null,
        status: null,
        type: null,
        destination: null,
        voyage: null,
        shippingCompany: null,
        transportType: null,
        vehicleNum: null,
        containerNum: null,
        expectedLeaveDate: null,
        expectedPackingDate: null,
        actualPackingDate: null,
        actualArrivalDate: null
      },
      // 订单导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/order/importData'
      }
    }
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    //    获取仓库数据
    getWarehouseList() {
      allWarehouse({}).then((res) => {
        this.warehouseList = res.data
      })
    },
    //车辆导入
    vehicleImport() {
      if (this.ids.length === 0) {
        return this.$message.error('请勾选一个订单')
      }
      if (this.ids.length > 1) {
        return this.$message.error('只允许勾选一个订单')
      }
      this.vehicleUpload.title = '车辆导入'
      this.vehicleUpload.open = true
    },

    //集装箱导入
    containerImport() {
      if (this.ids.length === 0) {
        return this.$message.error('请勾选一个订单')
      }
      if (this.ids.length > 1) {
        return this.$message.error('只允许勾选一个订单')
      }

      this.containersUpload.title = '集装箱导入'
      this.containersUpload.open = true
    },
    /** 查询订单-订单列表 */
    getList() {
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/system/order-info/index', query: { type: 'add' } })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push(
        { path: '/system/order-info/index', query: { orderId: row.orderId || this.ids, type: 'edit' } }
      )
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids
      this.$modal.confirm('是否确认删除订单-订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入';
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importOrderTemplate() {
      this.download('system/order/importTemplate', {}, `order_template_${new Date().getTime()}.xlsx`)
    },
    // 订单文件上传中处理
    handleFileOrderUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 订单文件上传成功处理
    handleFileOrderSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 订单提交上传文件
    submitFileOrderForm() {
      this.$refs.upload.submit()
    },
    /** 下载模板操作 */
    importContainerTemplate() {
      this.download('system/order/import/container/template', {}, `orderContainer_template_${new Date().getTime()}.xlsx`)
    },
    // 集装箱文件上传中处理
    handleFileContainerUploadProgress(event, file, fileList) {
      this.containersUpload.orderId = this.ids[0]
      this.containersUpload.isUploading = true
    },
    // 集装箱文件上传成功处理
    handleFileContainerSuccess(response, file, fileList) {
      this.containersUpload.open = false
      this.containersUpload.isUploading = false
      this.$refs.containersUpload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    submitFileContainersUploadForm() {
      this.$refs.containersUpload.submit()
    },
    //  关于车辆
    /** 下载模板操作 */
    importVehicleTemplate() {
      this.download('system/order/import/vehicle/template', {}, `orderVehicle_template_${new Date().getTime()}.xlsx`)
    },
    // 车辆文件上传中处理
    handleFileVehicleUploadProgress(event, file, fileList) {
      this.vehicleUpload.orderId = this.ids[0]
      this.vehicleUpload.isUploading = true
    },
    // 车辆文件上传成功处理
    handleFileVehicleSuccess(response, file, fileList) {
      this.vehicleUpload.open = false
      this.vehicleUpload.isUploading = false
      this.$refs.vehicleUpload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    submitFileVehicleUploadForm() {
      this.$refs.vehicleUpload.submit()
    }
  }
}
</script>
